// pages/repairAdd/repairAdd.js
const app = getApp();
import CommonService from '../../utils/service/commonService.js';
import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../utils/util');
import Base64 from '../../utils/Base64.js';
import {areaList} from '@vant/area-data';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参来的设备id
    equipmentId:null,
    //设备信息
    equipmentInfo:{},
    //提交按钮禁用
    disabled:false,
    //上传的图片
    imgUrls:[],
    //是否显示设备信息
    isShowInfo:false,
    //报修时间
    repairTime:util.timeFormat(new Date()),
    //报修时间选择框
    showTime:false,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    },
    //退出提示框
    showQuit:false,
    //提示
    showWeChatDia:false,
    //避免表单重复提交
    code:Base64.encode(new Date()+'repairRecord'),
    //设备选择框
    Equipment:false,
    //设备选择数据
    equipmentList:[],
    //设备编号是否只读
    isReadonly:false,
    //公众号名称
    officialName:'',
    //表单信息
    editInfo:{},
    //工单类型
    typeList:[{
        id:216,
        name:'维修工单',
        desc:'设备故障：维修工单'
      },{
        id:217,
        name:'耗材工单',
        desc:'耗材损耗：耗材工单'
      }
    ],
    //传参
    paramObj:null,
    //选择工单类型提示框
    showType:false,
    //省市区
    showArea: false,
    //省市区是否填写完整
    completeArea: false,
    //省市区组件的数据
		areaList,
		//显示提交按钮
		showSubmitBtn: false,
    //上传路径
    ossUploadUrl: app.globalData.ossUrl
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //有公众号的，扫码报修时提示关注公众号
    // let obj=wx.getLaunchOptionsSync();
    // if(obj.scene=='1047'){
    //   this.setData({
    //     showWeChatDia:true
    //   })
    // }

    this.setData({
      //公众号名称
      officialName: app.globalData.officialName,
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加报修传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })
      
      if(paramObj.equipmentId){
        this.setData({
          equipmentId: paramObj.equipmentId,
          isReadonly:true,
          isShowInfo:true
        })
        //获取设备信息
        this.getEquipmentInfo();
      }

      //工单类型
      if(paramObj.repairType){
        let repairType='editInfo.repairType';
        this.setData({            
          [repairType]: paramObj.repairType
        })
      }else{
        this.setData({
          showType: true
        })
      }

    }else{
      this.setData({
        showType: true
      })
    }  
  },

  //获取设备信息
  getEquipmentInfo(){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        id:this.data.equipmentId,
        selectFields:['id','equipmentNo','memberTypeName','project','dataAuthority','memberId','projectId','member','iconUrl','businessType','createDate','salesman','onAndOffState','imei','withdrawalAndEntry','afterSalesType','consumableGiftNumber','isZl','isfactoryBindNew']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data.result.length){
        let result=res.data.data.result[0];
        this.setData({
          equipmentInfo: result,
          equipmentNo:result.equipmentNo
        })

        //处理设备项目和地区
        this.equipmentTips(result);
      }
    }).catch((error) => {
    })
  },

  //处理设备项目、省市区、地址
  equipmentTips(result){
    if(result.project && result.project.length){
      if(result.project[0].area.province.id){
        let areaList=this.data.areaList;
        let province_list=areaList.province_list;
        let city_list=areaList.city_list;
        let county_list=areaList.county_list;

        let area=result.project[0].area;
        let province=area.province.name;
        let city=area.city.name;
        let district=area.district.name; 
        
        let provinceO={},cityO={},districtO={}; 
        
        for(let i in province_list){
          if(province==province_list[i]){
            provinceO={
              code: i,
              name: province_list[i]              
            }
          }
        }

        for(let i in city_list){
          if(city==city_list[i] || city+'市'==city_list[i]){
            cityO={
              code: i,
              name: city_list[i]              
            }
          }
        }

        for(let i in county_list){
          if(district==county_list[i]){
            districtO={
              code: i,
              name: county_list[i]
            }
          }
        }

        //省市区是否完整
        if(provinceO.name && cityO.name && districtO.name){
          this.setData({
            completeArea: true
          })
        }else{
          this.setData({
            completeArea: false
          })
        }
       
        let addressArea='editInfo.addressArea';
        let self_area='editInfo.self_area';
        this.setData({
          [addressArea]: [provinceO,cityO,districtO],
          [self_area]: [provinceO.name,cityO.name,districtO.name],
          address: result.project[0].addressDetail
        })

      }else{
        //无地区
        Toast.fail({
          duration: 5000,             
          message: '设备所属项目未设置地区'
        });
      }
    }else{
      //无项目
      Toast.fail({
        duration: 5000,             
        message: '设备无所属项目，请先设置'
      });
		}
		
		//不允许报修的设备，提交按钮不显示
		if(result.isZl){
			this.setData({
				showSubmitBtn: false
			})			
		}else{
			this.setData({
				showSubmitBtn: true
			})	
		}
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let user=app.globalData.userInfo;
    let obj=e.detail.value;
    let editInfo=this.data.editInfo;
    let eInfo=this.data.equipmentInfo;  

    let remark=obj.remark.trim(),
        contactPerson=obj.contactPerson.trim(),
        contact=obj.contact.trim(),
        address=obj.address.trim();

    let equipmentNo=null;
    let flag=false;
    let flagToday=false;

    if(this.data.equipmentId){
      equipmentNo=eInfo.equipmentNo;
      flag=true;
    }else{
      equipmentNo=obj.equipmentNo.trim();
      //非空验证
      if(!this.formNotEmpty(equipmentNo,'equipmentNoMessage','请输入设备编号')){
        return;
      }

      //验证设备是否存在
      flag=this.isExist(equipmentNo).then(value => {
        if(!value){
          this.setData({
            equipmentNoMessage: '设备不存在',
            disabled:true
          })
        }
        return value;
      });
    }

    //报修人必填
    if(!this.formNotEmpty(contactPerson,'contactPersonMessage','请输入报修人姓名')){
      return;
    }

    //手机号必填
    if(!this.formNotEmpty(contact,'contactMessage','请输入手机号')){
      return;
    }

    //手机号格式
    if(!util.checkPhoneFormat(contact)){
      this.setData({
        contactMessage: '手机号格式错误',
        disabled:true
      })
      return;
    }

    //今天是否已经报修过了
    flagToday=this.isExistToday(equipmentNo,editInfo.repairType).then(value => {
      if(value){
        this.setData({
          disabled:true
        })
        Toast.fail('每台设备当天最多报修三次')
      }
      return !value;
    });

    //省市区
    if(!this.data.completeArea){
      Toast.fail('收货地区不完整');
      return;
    }

    //设备问题/所需耗材必填
    let strs = editInfo.repairType==216 ? '设备问题' : '所需耗材'
    if(!this.formNotEmpty(remark,'remarkMessage','请输入'+strs)){
      return;
    }

    Promise.all([flag,flagToday]).then(value => {
      let passed=value.every(val=>{
        return val;
      });

      if(passed){
        //处理权限
        let dataAuthorityArr=eInfo.dataAuthority.depart;
        if(user){
          dataAuthorityArr.push(user.departObj[0].companyId,user.depart,eInfo.memberId);
        }else{
          dataAuthorityArr.push(eInfo.memberId);
        }
        //去掉空值
        let dataAuthorityArrNew=[];
        dataAuthorityArr.forEach(item => {
            if(item){
                dataAuthorityArrNew.push(item);
            }
        });
        //去重
        let dataAuthoritySet=new Set(dataAuthorityArrNew);
        dataAuthorityArrNew=Array.from(dataAuthoritySet);
        
        //处理入场日期
        let outDate = eInfo.createDate;
        if(eInfo.withdrawalAndEntry && eInfo.withdrawalAndEntry.length){
          //倒序遍历设备出入场记录
          let wList = eInfo.withdrawalAndEntry;
          for(let i=wList.length-1; i >= 0; i--){
            //当前记录没有撤场时间
            if(!wList[i].withdrawalTime){
              //当前记录是设备所在机构的记录
              if(eInfo.memberId==wList[i].memberId){
                //项目信息是否为空
                if(eInfo.project && eInfo.project.length){
                  //判断当前记录是否为设备所在项目记录
                  if(eInfo.project[0].id==wList[i].projectId){
                    if(wList[i].admissionTime){
                      //转成日期类型方便比较
                      let cTime = new Date((eInfo.createDate).replaceAll("-","/"))
                      let aTime = new Date(wList[i].admissionTime);
                      //创建时间是否在入场时间之前
                      if (cTime < aTime) {
                        //将创建时间，改为入场时间
                        outDate = util.timeFormat(aTime);
                      }
                    }
                  }
                }
              }
            }
          }
        }

        let param={
          //设备编码
          equipmentNo: equipmentNo,
          //设备ID
          equipmentId: eInfo.id,
          //工单类型
          orderType:{
            id: editInfo.repairType,
            name: editInfo.repairType==216 ? '维修工单' : '耗材工单'
					},
					//是否耗材工单
          isConsumable: editInfo.repairType==217 ? true : false,
          //设备类型
          memberTypeName: eInfo.memberTypeName,
          //报修人信息
          repairMan:{
            name: obj.contactPerson,
            phone: contact
          },
          //省市区
          addressArea: editInfo.addressArea,
          //地址
          address: address,
          //报修时间
          repairDate: util.timeFormat(new Date()),
          //数据来源：1电话，2微信小程序，3第三方
          dataSource: 2,
          //图片
          pic: JSON.stringify(this.data.imgUrls),
          //问题描述
          repairQuestion: remark,
          //平台
          appId: [app.globalData.myAppId],
          //权限
          dataAuthority:{
            depart:dataAuthorityArrNew
          },
          //业务类型
          businessType: eInfo.businessType,         
          //入场日期
          createDate: outDate,
          //请求源
          requestSource: app.globalData.domainName,
          //停机状态
          isShutDown: eInfo.onAndOffState ? eInfo.onAndOffState : '',
          //创建人
          createUser:{
            id: user && user.id ? user.id : null,
            name: user && user.userName ? user.userName : '公众号报修'
          },
          //物联网编码
          imei: eInfo.imei,
          //售后类型 线上/线下
          afterSalesType: eInfo.afterSalesType,
          //耗材赠送套数
          consumableGiftNumber: eInfo.consumableGiftNumber
				}

				//2024-12-18修改，如果不是订单绑定的（isfactoryBindNew不是true的）只能提维修工单
				if(!eInfo.isfactoryBindNew){
					param.orderType = {
						id: 216,
						name: '维修工单'
					}
					param.isConsumable = false;
				}

        //客户机构
        if(eInfo.member.length){
          param.depart={
            id: eInfo.memberId,
            name: eInfo.member[0].name,
            code: eInfo.member[0].code ? eInfo.member[0].code : null
          }
        }

        //所在项目
        if(eInfo.project.length){
          param.project={
            id: eInfo.projectId,
            name: eInfo.project[0].name,
            code: eInfo.project[0].code ? eInfo.project[0].code : null
          }

          //地区(省)（暂时-如果项目无地区则指派给徐海亮的江苏省）
          if(eInfo.project[0].area && eInfo.project[0].area.province && eInfo.project[0].area.province.id){
            param.area={
              id: eInfo.project[0].area.province.id,
              name: eInfo.project[0].area.province.name,
              level: '1'
            }
          }else{
            param.area={
              id: 11,
              name: '江苏省',
              level: '1'
            }
          }
        }else{
          Toast.fail({
            duration: 5000,
            message: '设备无所属项目，请先设置'
          });
          return;
        }

        //业务员
        if(eInfo.salesman){
          param.salesman={
            id: eInfo.salesman.id,
            name: eInfo.salesman.userName ? eInfo.salesman.userName : eInfo.salesman.name,
            code: eInfo.salesman.code
          }
        }
        
        // console.log('~报修~');
        // console.log(param);
        // return;

        //避免表单重复提交
        Toast.loading({
          duration: 0,
          forbidClick: true,
          message: '数据提交中...'
        });

        CommonService.addRepair(param).then(res=>{
          if (res.statusCode == 200 && res.data.success == true && res.data.data.success==true){
            Toast.clear();
            this.setData({
              disabled:false
            })            

            if(user){
              Toast.success('成功');
              setTimeout(() => {
                //跳转列表
                if(editInfo.repairType==216){              
                  wx.reLaunch({
                    url: "/packageA/pages/repairList/repairList"
                  })
                }else if(editInfo.repairType==217){
                  wx.reLaunch({
                    url: "/packageA/pages/consumableList/consumableList"
                  })
                }
              }, 1000);
            }else{
              this.setData({
                showQuit: true
              })
            }  

          }else if(res.statusCode==202){
            Toast.fail('您操作太快了,请勿重复提交');
          }else{
            Toast.fail('操作失败，请联系管理员');
          }
        }).catch((error) => {
          Toast.fail('操作失败，请联系管理员');
        })

      }
    });
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      this.setData({
        imgUrls: imgUrls
      })
    }
  },

  //扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        _this.setData({
          equipmentNo: res.result
        })
        //查询设备
        this.findEquipment(_this.data.equipmentNo);
      },
      fail(){
        Toast.fail('扫码失败请重试');
        _this.setData({
          equipmentNo: ''
        })
      }
    })
  },  

  //显示报修时间选择框
  onShowTime(){
    this.setData({
      showTime: true
    })
  },

  //隐藏报修时间选择框
  onCloseTime(){
    this.setData({
      showTime: false
    })
  },

  //确认报修时间
  onConfirmTime(e) {
    this.setData({
      currentDate: e.detail,
      repairTime:util.timeFormat(e.detail),
    });
    this.onCloseTime();
  },

  //验证设备是否存在
  isExist(equipmentNo){
    return new Promise((resolve, reject) => {
      let param={
        isAuth:false,
        className:'equipment',
        data:{
          equipmentNo:equipmentNo,
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          selectFields:["id"]
        }
      }
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.count && res.data.data.result) {
          resolve(true);
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //今天是否已报修超过3次
  isExistToday(equipmentNo,type){
    let className='';
    if(type==216){
      className='afterSaleMaintainOrder';
    }else if(type==217){
      className='afterSaleConsumableOrder';
    }

    return new Promise((resolve, reject) => {
      let param={
        isAuth:false,
        className:className,
        data:{
          searchAll: true,
          equipmentNo: equipmentNo,
          createDate:{
            '>':util.timeFormatDay(new Date())+' 00:00:00'
          },
          state:{
            '!=':1
          },
          nbl:Base64.encode(util.timeFormatDay(new Date())),
          selectFields:["id"]
        }
      }
      CommonService.goFindList(param).then(res=>{
        if (res.data.data && res.data.data.count && res.data.data.result) {
          if(res.data.data.count>=3){
            resolve(true);
          }else{
            resolve(false);
          }
        } else {
          resolve(false);
        }
      }).catch((error) => {
        resolve(false);
      })
    });
  },

  //确认-跳转关注公众号
  confirmWeChat(){
    wx.navigateTo({
      url: "/pages/weChatOfficial/weChatOfficial"
    })
  },  

  //设备编号输入框失去焦点
  onBlur(e){
    let no=e.detail.value.trim();
    if(no){
      //查询设备
      this.findEquipment(no);
    }
  },

  //查询设备
  findEquipment(no){
    let param={
      isAuth:false,
      className:'equipment',
      data:{
        searchAll: true,
        equipmentNo:no,
        nbl:Base64.encode(util.timeFormatDay(new Date())),
        selectFields:['id','equipmentNo','memberTypeName','project','dataAuthority','memberId','projectId','member','iconUrl','businessType','createDate','salesman','onAndOffState','imei','withdrawalAndEntry','afterSalesType','consumableGiftNumber','isZl','isfactoryBindNew']  
      }
    }
    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.count && res.data.data.result){
        if(res.data.data.count==1){
          let result=res.data.data.result[0];
          this.setData({
            isShowInfo:true,
            equipmentInfo: result
          })

          //处理设备项目和地区
          this.equipmentTips(result);
        }

        if(res.data.data.count>1){
          let list=res.data.data.result;
          let arr=[];
          for(let i=0;i<list.length;i++){
            let obj={
              text:list[i].equipmentNo +' '+ list[i].project[0].name,
              id:list[i].id,
              obj:list[i]
            }
            arr.push(obj);
          }

          //有多台设备时显示设备选择
          this.setData({
            showEquipment: true,
            equipmentList: arr
          })
        }
      }else{
        this.setData({
          equipmentNoMessage: '设备不存在',
          disabled:true,
          isShowInfo:false
        })
      }
    }).catch((error) => {
    })

  },

  //隐藏设备选择框
  onCloseEquipment(){
    this.setData({
			showEquipment: false
    })
  },

  //确认设备
  onConfirmEquipment(e){
    let obj=e.detail.value.obj;  

    this.setData({
      equipmentInfo: obj
    })

    //处理设备项目和地区
    this.equipmentTips(obj);

    this.onCloseEquipment();
  },

  //预览图片
  onPreviewImage(e) {
    let src = e.target.dataset.src;
    wx.previewImage({
      current: src,
      urls: [src]
    })
  },

  //工单类型
  onChangeType(event) {
    let repairType='editInfo.repairType';
    this.setData({
      [repairType]: event.detail,
    })
  },  

  //点击选择工单类型
  onClickType(event) {
    const {name} = event.currentTarget.dataset;
    let repairType='editInfo.repairType';
    this.setData({
      [repairType]: name,
    })
  },

  //确认工单类型
  onConfirmType(){
    if(this.data.editInfo.repairType){
      this.setData({
        showType: false
      })
    }else{
      Toast.fail('请选择工单类型');
    }
  },

  //显示省市区
  onShowArea(){
    this.setData({
			showArea: true
    })
  },

  //隐藏省市区
  onCloseArea(){
    this.setData({
			showArea: false
    })
  },

  //确认省市区
  onConfirmArea({detail}){
    let arr=detail.values;   
    let names=[];
    arr.forEach(item=>{
      names.push(item.name);
    });

    let addressArea='editInfo.addressArea';
    let self_area='editInfo.self_area';
    this.setData({
      [addressArea]: arr,
      [self_area]: names,
      disabled: false,
      completeArea: true
    })

    this.onCloseArea();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
